import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter - FastAPI Communication',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter - FastAPI Communication'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _response = '';

  Future<void> _fetchData() async {
    final response = await http.get(Uri.parse('http://192.168.1.118:3100/hello'));

    if (response.statusCode == 200) {
      setState(() {
        _response = json.decode(response.body).toString();
      });
    } else {
      setState(() {
        _response = 'Failed to load data';
      });
    }
  }

  Future<void> _sendData() async {
    final data = {'message': 'Hello from Flutter'};
    final response = await http.post(
      Uri.parse('http://192.168.1.118:3100/data'),
      headers: {'Content-Type': 'application/json'},
      body: json.encode(data),
    );

    if (response.statusCode == 200) {
      setState(() {
        _response = json.decode(response.body).toString();
      });
    } else {
      setState(() {
        _response = 'Failed to send data';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: _fetchData,
              child: Text('Fetch Data from FastAPI'),
            ),
            ElevatedButton(
              onPressed: _sendData,
              child: Text('Send Data to FastAPI'),
            ),
            Text(
              'Response: $_response',
            ),
          ],
        ),
      ),
    );
  }
}